package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 分页操作
        IPage<Brand> iPage = new Page<>(page, rows);
        // 查询key是否存在
        Boolean isKeyExist = StringUtils.isNotBlank(key);

        page(iPage, new QueryWrapper<Brand>()
                .like(isKeyExist, "name", key)
                .or()
                .eq(isKeyExist, "letter", key));
        return new PageDTO<>(iPage.getTotal(), iPage.getPages(), BrandDTO.convertEntityList(iPage.getRecords()));
    }

    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        this.saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    private void saveCategoryBrand(List<Long> categoryIds, Long id) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(cid-> CategoryBrand.of(cid, id))
                .collect(Collectors.toList());
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        updateById(brand);
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    @Override
    @Transactional
    public void deleteBrand(Long id) {
        removeById(id);
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }

}
